<?php
/**
 * Admin Service
 * User: zng
 * Date: 2019/11/4
 * Time: 14:34
 */
namespace app\admin\service;

use app\admin\model\admin\Admin as AdminModel;
use gmars\rbac\model\AdminRole;
use think\Exception;
use think\facade\{
    Cache,Request,Session
};
use app\exceptions\{
    OrdinaryException,PowerException
};
use other\Token;

Class Admin {

    /**
     * 登录操作
     * @author zx
     * @date 2019-11-04
     * @return \think\response
     */
    public function login( array $post )
    {
        $adminModel = AdminModel::login($post['username'])->findOrEmpty();
        if ( $adminModel->isEmpty() ) {
            return failed('账户或密码错误');
        }
        if ( ! password_verify( $post['password'], $adminModel->password ) ) {
            return failed('账户或密码错误');
        }
        if ( $adminModel->type == 0 && $adminModel->status != 0 ) {
            return failed('您的账户已被禁用!请联系管理员解封');
        }
        $adminModel->last_login_at = date("Y-m-d H:i:s", time());
        $adminModel->last_login_ip = Request::ip();
        $adminData = clone $adminModel;
        $adminModel->login_count = ['inc', 1];
        $adminModel->save();
        $adminData->login_count += 1;
        unset($adminData->password);
        $cacheTime = get($post, 'online')==1?0:86400;
        if ( $adminModel->type != 1 ) {
            try {
                app('rbac')->cachePermission($adminData->id, $cacheTime);
            } catch (Exception $exception) {
                throw new OrdinaryException($exception->getMessage());
            }
        }
        $token = Token::encode($adminData->toArray());
        cookie('Huiskin', $adminData->skin??'default');
        session('token', $token);
        return success();
    }

    /**
     * 退出
     * @author zx
     * @date 2019-12-06
     * @return \think\response
     */
    public function logout()
    {
        $cacheName = Session::get('gmars_rbac_permission_name');
        Session::clear();
        Cache::rm($cacheName);
        return success();
    }

    /**
     * 首页列表
     * @author zx
     * @date 2019-11-08
     * @return \think\Paginator
     */
    public function indexPaginate( array $get=[] )
    {
        $map = [];
        if ( get($get, 'username') ) {
            $map[] = ['username', 'LIKE', '%'.$get['username'].'%'];
        }
        if ( get($get, 'mobile') ) {
            $map[] = ['mobile', '=', $get['mobile']];
        }
        $status = get($get, 'status');
        if ( $status === 0 || $status === '0' || $status == 1 ) {
            $map[] = ['status', '=', $status];
        }
        if ( get($get, 'start_create_at') ) {
            $map[] = ['create_at', '>=', $get['start_create_at'].' 00:00:00'];
        }
        if ( get($get, 'end_create_at') ) {
            $map[] = ['create_at', '<=', $get['end_create_at'].' 23:59:59'];
        }
        $pageSize = get($get,'pageSize')>0?$get['pageSize']:20;
        return AdminModel::where($map)->field('password,delete_at', true)
            ->order('id', 'desc')
            ->paginate($pageSize);
    }

    /**
     * 更改状态
     * @author zx
     * @date 2019-11-11
     * @return \think\response
     */
    public function status(AdminModel $admin)
    {
        if ( $admin->type == 1 ) {
            return failed('该用户为超级管理员,不可禁用');
        }
        $status = (int)(!$admin->status);
        $admin->status = $status;
        $update = $admin->save();
        if ( $update ) {
            return success(['status'=>$status]);
        }
        return failed('更新失败');
    }

    /**
     * 获取管理详情
     * @param int $id
     * @author zx
     * @date 2019-11-11
     * @return array
     */
    public function get(int $id)
    {
        if ( $id <= 0 )
            return [];
        $adminModel = AdminModel::findOrEmpty($id);
        if ( $adminModel->isEmpty() )
            return [];

        return $adminModel->toArray();
    }

    /**
     * 更改管理员信息
     * @param int $id
     * @param array $data 数据包
     * @author zx
     * @date 2019-11-12
     * @return boolean
     */
    public function save(int $id, array $data)
    {
        return (new AdminModel())
            ->allowField(['password','mobile','skin'])
            ->isUpdate()->save($data, ['id'=>$id]);
    }

    /**
     * 新增管理员信息
     * @param array $data 数据包
     * @author zx
     * @date 2019-11-12
     * @return boolean|integer
     */
    public function create(array $data)
    {
        $admin = AdminModel::create($data, ['username','password','mobile']);
        return $admin->isEmpty()?false:$admin->id;
    }

    /**
     * 给管理员分配角色
     * @param int $id
     * @param array $rid 角色列表
     * @author zx
     * @date 2019-11-12
     * @throws Exception
     * @return boolean
     */
    public function role( int $id, array $rid )
    {
        app('rbac')->assignUserRole($id, $rid);
        return true;
    }

    /**
     * 获取角色列表
     * @param int $id
     * @author zx
     * @date 2019-11-12
     * @return array
     */
    public function getRole(int $id)
    {
        return AdminRole::where('user_id', $id)->column('role_id');
    }

    /**
     * 判断是否唯一
     * @param array $data
     * @author zx
     * @date 2019-11-12
     * @return boolean
     */
    public function only(array $data)
    {
        $map = [];
        $id = get($data, 'id', 0);
        if ( get($data, 'username') ) {
            $map[] = ['username', '=', $data['username']];
        }
        if ( $id <= 0 ) {
            $count = AdminModel::where($map)->count();
            if ( $count > 0 ) {
                return false;
            }
        } else {
            $idResult = AdminModel::where($map)->column('id');
            foreach ( $idResult as $_id ) {
                if ( $_id != $id ) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 批量删除
     * @param mixed $data
     * @author zx
     * @date 2019-11-12
     * @return boolean
     */
    public function destory( $data )
    {
        return AdminModel::destroy(function($query)use($data){
            $where = ['id', '=', $data];
            if ( is_array($data) ) {
                $where = ['id', 'in', $data];
            }
            $query->where([
               ['type', '=', 0],
                $where
            ]);
        });
    }

    /**
     * 判断是否越权
     * @param int $type 当前管理员类型
     * @param int $id 当前管理员ID
     * @author zx
     * @date 2019-12-06
     * @throws PowerException
     * @return bool
     */
    public function ultraVires(int $type, int $id)
    {
        $admin = $this->get($id);
        if ( $type != 1 && $admin['type'] != $type ) {
            throw new PowerException('您的操作已越权');
        }
        return false;
    }


}